<template>
  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入关键字查询" style="width: 200px" v-model="data.name"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load()">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="card">
      <div style="margin-bottom: 10px">
        <el-button type="primary" plain @click="handleAdd">新增</el-button>
        <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      </div>
      <el-table :data="data.tableData" strip @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
<!--        <el-table-column prop="id" label="序号" width="70" align="center" sortable></el-table-column>-->
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="name" label="用户姓名"></el-table-column>
        <el-table-column prop="gender" label="性别">
          <template v-slot="scope">
            <span>{{ scope.row.gender === 'Male' ? '男' : scope.row.gender === 'Female' ? '女' : '其他'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="birthdate" label="出生日期" width="120"></el-table-column>
        <el-table-column prop="phoneNumber" label="手机号" width="120"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-tag :type="scope.row.status === 'Active' ? 'success' : 'danger'">
              {{ scope.row.status === 'Active' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="用户注册时间" width="170"></el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="170"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            style="margin-top: 5px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNum"
            :page-sizes="[3, 5, 10, 15, 20]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total">
        </el-pagination>
      </div>
    </div>



    <el-dialog title="用户信息" v-model="data.formVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="userRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="data.form.password" placeholder="用户密码" disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="data.form.name" placeholder="用户姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="data.form.gender">
            <el-radio label="Male">男</el-radio>
            <el-radio label="Female">女</el-radio>
            <el-radio label="Other">其他</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="出生日期" prop="birthdate">
          <el-date-picker
              v-model="data.form.birthdate"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="data.form.phoneNumber" placeholder="手机号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script setup>
import {reactive, ref} from 'vue'
import request from '@/utils/request'
import {ElMessage, ElMessageBox} from 'element-plus'
// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
// 定义响应式数据
const data = reactive({
  tableData: [],  // 表格数据
  pageNum: 1,     // 当前页码
  pageSize: 10,   // 每页显示数量
  total: 0,       // 总记录数
  name: null,     // 搜索条件
  formVisible: false, // 表单显示状态
  form: {},       // 表单数据
  ids: [],        // 选中数据的ID
})
// 分页查询
const load = () => {
  request.get('/user/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      role: 'Expert'
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}
load()
// 新增数据
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
  console.log(data.formVisible)
}

// 编辑数据
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

// 保存数据
const save = () => {
  const url = data.form.id ? '/user/update' : '/user/add'
  const method = data.form.id ? 'PUT' : 'POST'
  data.form.role = 'Expert'
  request({
    url,
    method,
    data: data.form,
  }).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('保存成功')
      data.formVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}


// 删除单条数据
const del = (id) => {
  ElMessageBox.confirm('您确定删除吗？', '确认删除', {type: 'warning'}).then(() => {
    request.delete('/user/delete/' + id).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
  })
}


// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('您确定批量删除这些数据吗？', '确认删除', {type: 'warning'}).then(() => {
    request.delete('/user/delete/batch', {data: data.ids}).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
  })
}

// 处理选中的行
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

// 重置筛选条件
const reset = () => {
  data.name = null
  load()
}
// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum
  load(pageNum)
}
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize
  load()
}
const userRef = ref()
const submitForm = () => {
  userRef.value.validate((valid) => {
    if (valid) {
      save()
    } else {
      ElMessage.error('请填写必须的参数！')
      return false
    }
  })
}
const rules = {
  name: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' },
    { min: 2, max: 15, message: '患者姓名长度需在2-15个字符之内', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' },
    { min: 2, max: 15, message: '患者姓名长度需在2-15个字符之内', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthdate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  phoneNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式有误', trigger: 'blur' }
  ]
}
</script>


<style scoped>
.user-management {
  padding: 20px;
  background-color: #f9f9f9;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.operation-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.user-table {
  margin-top: 15px;
  background-color: #fff;
}

.pagination {
  margin: 15px 0;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
  padding: 10px 0;
}

.user-form .el-form-item {
  margin-bottom: 12px;
}
</style>